<template>
  <a-modal
    :visible="visible"
    title="渠道抽佣比例设置"
    :mask-closable="false"
    class="modal-dialog-wrapper"
    unmount-on-close
    @ok="onOk"
    @cancel="onCancel"
    hide-cancel
    width="55vw"
    :body-style="{
      padding: '11px 20px',
    }"
  >
    <div style="max-height: 80vh">
      <table-modal ref="tableModalRef" @submit="submit" />

      <a-button class="mt-4 mb-4 w-full" type="primary" @click="onAddChannel">
        <template #icon>
          <icon-plus />
        </template>
        新增渠道
      </a-button>
    </div>
  </a-modal>

  <SysdictModal ref="sysdictModal" maxLength="99999" @save="saveOk" />
</template>

<script setup lang="ts">
  import SysdictModal from '@/components/sysdict/sysdict-modal.vue'
  import TableModal from '@/views/system/general/commission-settings/components/table-modal.vue'

  import { updateCommission } from '@/api/system/commission'

  import { ref, watch } from 'vue'

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
  })

  const emits = defineEmits(['update:visible', 'ok'])
  const sysdictModal = ref()
  const tableModalRef = ref()

  const dictCode = 'short_order_channel_type'

  const onAddChannel = () => {
    sysdictModal.value.show(null, dictCode)
  }

  const saveOk = () => {
    if (tableModalRef.value) {
      tableModalRef.value.loadData()
    }
  }

  const submit = (record: any) => {
    const param = [
      {
        id: record.id,
        channelType: record.channelType,
        subject: record.subject,
        commissionRate: record.commissionRate,
        operateSource: 2,
      },
    ]

    updateCommission(param).then(() => {
      if (tableModalRef.value) {
        tableModalRef.value.loadData()
      }
    })
  }

  const onOk = () => {
    emits('update:visible', false)
  }

  const onCancel = () => {
    emits('update:visible', false)
  }

  watch(
    () => props.visible,
    (newVal) => emits('update:visible', newVal)
  )
</script>

<style lang="less" scoped>
  .custom-modal {
    // 修改弹窗蒙层样式
    .w-49 {
      width: 49%;
    }
  }
</style>
